/*
 * @Author: wangyongcun
 * @Date: 2023-02-21 18:54:52
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-06-10 08:57:11
 * @Description: aixos 请求扩展 & 初始化 & 拦截
 */
import axios from "axios"; // axios
import { ElMessage } from "element-plus"; // 统一提醒
import { userStore } from "@/stores/userInfo"; // 获取用户信息，用来判断是否登录过期
const ElMessageDuration = 2000;

/* 实例化-axios */
const instance = axios.create({
  baseURL: "/api", //默认请求前缀
  timeout: 1000 * 60, //默认响应过期
});

/* 请求拦截 */
instance.interceptors.request.use(
  (config) => {
    // 添加token
    const userInfo = userStore();
    if (userInfo.$state.token) {
      config.headers.token = userInfo.$state.token;
    }
    // 返回请求体
    return config;
  },
  (error) => {
    return Promise.reject(error); // 为了可以在代码中catch到错误信息
  }
);

/* 响应拦截*/
instance.interceptors.response.use(
  async (response) => {
    const res = response.data;
    const userInfo = userStore();
    // 更新token
    if (response.headers.token) {
      userInfo.$state.token = response.headers.token;
    }
    // token过期处理, 跳转至登录页面
    if (res.code == 'A0344') {
      userInfo.$reset();
      ElMessage({
        message: "登录已过期，请重新登录",
        type: "warning",
        grouping: true,
        duration: ElMessageDuration,
      });
      setTimeout(() => {
        window.location.href = "/manageSystem/login";
      }, ElMessageDuration);
    } else {
      //自动提醒处理
      const autoTip = response.config.headers.autoTip;
      if (autoTip === "true" || autoTip === res.result) {
        ElMessage({
          message: res.message,
          type: res.result == "success" ? "success" : "error",
        });
      }
      return response.data;
    }
  },
  (error) => {
    ElMessage({
      message: "请求出错了，请稍后重试",
      type: "error",
      grouping: true,
      duration: ElMessageDuration,
    });
    return Promise.reject(error);
  }
);

export const Request = instance;
